package com.example.service;

import com.example.entity.Driver;
import com.example.entity.DriverStatus;
import com.example.entity.Vehicle;
import com.example.entity.VehicleStatus;
import com.example.repository.DriverRepository;
import com.example.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DriverService {
    private final DriverRepository driverRepository;
    private final VehicleRepository vehicleRepository;

    @Autowired
    public DriverService(DriverRepository driverRepository, VehicleRepository vehicleRepository) {
        this.driverRepository = driverRepository;
        this.vehicleRepository = vehicleRepository;
    }

    public String applyForJoining(Driver driver, Vehicle vehicle) {
        // 检查 license_number 是否重复
        if (driverRepository.existsById(driver.getLicenseNumber())) {
            return "该驾驶证及司机已经添加！";
        }
        // 检查车牌是否重复
        if (vehicleRepository.existsById(vehicle.getLicensePlate())) {
            return "该车牌已被使用！";
        }
        // 直接通过加盟申请，设置状态为 APPROVED
        driver.setStatus(DriverStatus.APPROVED);
        vehicle.setStatus(VehicleStatus.AVAILABLE);
        vehicleRepository.save(vehicle);
        driverRepository.save(driver);
        return "司机加盟申请已通过，车辆信息已同步。";
    }
}
